package com.jxwifi.cloud.quickclean.mycenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.AssOrderAdapter;
import com.jxwifi.cloud.quickclean.adapter.GradeRankAdapter;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.assemble.ADetailsActivity;
import com.jxwifi.cloud.quickclean.assemble.AssembleOrderPresenter;
import com.jxwifi.cloud.quickclean.assemble.AssembleOrderView;
import com.jxwifi.cloud.quickclean.bean.CollageRecordsBean;
import com.jxwifi.cloud.quickclean.bean.RankingBean;
import com.jxwifi.cloud.quickclean.bean.RespBaseBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GradeRankActivity extends ClientBasicActivity{

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.rv_grade_rank_list)
    RecyclerView rv_grade_rank_list;
    @Bind(R.id.srl_grade_rank_list)
    SuperSwipeRefreshLayout srl_grade_rank_list;
    @Bind(R.id.rel_list_null)
    RelativeLayout rel_list_null;

    private int mLimit=20;
    private GradeRankAdapter mAdapter;
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;

    private int mCurrentCounter;//获取的数据个数
    private int mPageIndex = 1;
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    private boolean isErr = true;
    private AuzImpl mAuz;
    private List<RankingBean> mBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grade_rank);
        ButterKnife.bind(this);
        openEventBus();
        mAuz = new AuzImpl();
        initView();
    }

    @OnClick({R.id.rel_img_back_pressed})
    void clickCK(View v){
        switch (v.getId()){
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
        }
    }

    @Subscriber(tag = "e-wx-success")
    private void getWXsuccess(RespBaseBean mBean) {
        if (mBean != null) {
            switch (mBean.getTyoe()) {
                case StateUtils.WE_CHAT_SHARE:
                    Toast toast = Toast.makeText(mBaseContext, "分享成功", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    break;
                case StateUtils.WE_CHAT_LOGIN:
                    break;
                case StateUtils.QQ_LOGIN:
                    break;
            }
        }
    }


    @Subscriber(tag = "e-wx-cancel")
    private void getWXcancel(RespBaseBean mBean) {
        if (mBean != null) {
            switch (mBean.getTyoe()) {
                case StateUtils.WE_CHAT_SHARE:
                    Toast toast = Toast.makeText(mBaseContext, "取消分享", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    break;
                case StateUtils.WE_CHAT_LOGIN:
                    break;
                case StateUtils.QQ_LOGIN:
                    break;
            }
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    public void initView(){
        rv_grade_rank_list.setLayoutManager(new LinearLayoutManager(this));
        rv_grade_rank_list.setAdapter(mAdapter = new GradeRankAdapter(R.layout.activity_grade_rank_item));
        initData();

        //上拉加载更多操作
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                rv_grade_rank_list.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentCounter >= mTotalNum) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                        } else {
                            if (isErr) {
                                initData();
                                //成功获取更多数据
                                mCurrentCounter = mAdapter.getData().size();
                                mAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
                                isErr = true;
                                Toast.makeText(GradeRankActivity.this, "获取更多数据失败", Toast.LENGTH_LONG).show();
                                mAdapter.loadMoreFail();
                            }
                        }
                    }
                }, 1500);

            }
        }, rv_grade_rank_list);

        srl_grade_rank_list.setHeaderView(createHeaderView());
        srl_grade_rank_list.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        srl_grade_rank_list.setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        mPageIndex = 1;
                        initData();
                    }
                }, 1000);
            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(srl_grade_rank_list.getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    public void initData(){  //CollageRecordsBean

        Params params = new Params();
        mAuz.auzget(UrlPool.GET_GRADE_RANK, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0){
                    Gson gson = new Gson();
                    mBeanList = gson.fromJson(data,new TypeToken<List<RankingBean>>(){}.getType());
                    /*for (int i = 0; i < mBeanList.size(); i++) {
                        Log.i(TAG,mBeanList.get(i).getVip()+" "+mBeanList.get(i).getNickName()+" "+mBeanList.get(i).getTellTemp());
                    }*/
                    if( mBeanList.size()>0){
                        if (mPageIndex == 1){
                            setData(true, mBeanList);
                        }else{
                            setData(false, mBeanList);
                        }
                        //mAdapter.setNewData(mBeanList.getRecords());
                    }else{
                        rv_grade_rank_list.setVisibility(View.GONE);
                        rel_list_null.setVisibility(View.VISIBLE);
                        srl_grade_rank_list.setEnabled(false);
                    }
                }
                //mBeanList= JSON.parseObject(data, RankingBean.class);
                //Log.i(TAG,"mBeanList.getSize = "+mBeanList.getSize());

                /*if (mBeanList.getSize()>0){
                    mView.getOrderList().setVisibility(View.VISIBLE);
                    mView.getListNull().setVisibility(View.GONE);
                    if (mPageIndex == 1){
                        setData(true, mBeanList.getRecords());
                    }else{
                        setData(false, mBeanList.getRecords());
                    }
                    //mAdapter.setNewData(mBeanList.getRecords());
                }else{
                    mView.getOrderList().setVisibility(View.GONE);
                    mView.getListNull().setVisibility(View.VISIBLE);
                    mView.getSwip().setEnabled(false);
                }*/
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                //mView.onFailure(errorCode, msg);
            }
        });
    }

    public void setData(boolean isRefresh, List data) {
        Log.i(TAG,"mPageIndex = "+mPageIndex);
        mPageIndex++;
        final int size = data == null ? 0 : data.size();

        if (isRefresh) {
            srl_grade_rank_list.setEnabled(true);
            mAdapter.setNewData(data);

        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        mCurrentCounter = mAdapter.getData().size();
        if (size < mLimit) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }


}
